package com.zxm.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.zxm.common.core.domain.entity.QQPo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Author silence.Z
 * @Date 2022/8/3 14:52
 * @PackageName:com.zxm.common.utils
 * @ClassName: QQUtil
 * @Description: 根据QQ号码获取QQ信息
 * @Version 1.0
 */
public class QQUtil {
	private static String getQQJsonStr(Long qqId) {
		StringBuilder jsonString = new StringBuilder();
		URLConnection connection = null;
		try {
			URL urlObject = new URL("https://users.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?uins=" + qqId);
			connection = urlObject.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				jsonString.append(inputLine);
			}
			in.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonString.toString().substring("portraitCallBack(".length(), jsonString.length() - 1);
	}

	public static QQPo getQQInfo(Long qqId) {
		String jsonString = getQQJsonStr(qqId);
		JSONObject jsonObject = JSON.parseObject(jsonString);
		JSONArray jsonArray = jsonObject.getJSONArray(String.valueOf(qqId));
		return QQPo.builder().id(qqId)
				.name((String) jsonArray.get(6))
				.avatar(jsonArray.get(0).toString().replaceAll("http", "https"))
				.build();
	}

	public static void main(String args[]) {
		System.out.println(getQQInfo(2364201071L));
	}
}
